// pages/notice/list/index.ts
import NoticeApi from "../../../api/NoticeApi"
import Toast from "tdesign-miniprogram/toast/index"

Page({

  /**
   * 页面的初始数据
   */
  data: {
    list: [],
    title: ''
  },
  pageNum: 1,
  pageSize: 10,
  total: 0,
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    this.getList()
  },
  getList() {
    const { title } = this.data
    NoticeApi.page({ index: this.pageNum, size: this.pageSize, title }).then((res: any) => {
      let list = res.data.map((i: Notice) => {
        i.createTime = i.createTime?.substring(0, 10)
        return i
      })
      this.setData({ list })
      this.total = res.total
    }).catch(e => {
      Toast({
        context: this,
        selector: '#t-toast',
        message: e,
      })
    })
  },
  addList() {
    const { title } = this.data
    NoticeApi.page({ index: this.pageNum, size: this.pageSize, title }).then((res: any) => {
      let list = res.data.map((i: Notice) => {
        i.createTime = i.createTime?.substring(0, 10)
        return i
      })
      this.setData({ list: this.data.list.concat(list) })
      this.total = res.total
    }).catch(e => {
      Toast({
        context: this,
        selector: '#t-toast',
        message: e,
      })
    })
  },
  handleFilter() {
    this.pageNum = 1
    this.getList()
  },
  handleDetail(e: any) {
    const id: string = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/notice/detail/index?id=${id}`
    })
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.handleFilter()
    wx.stopPullDownRefresh()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    this.pageNum += 1
    this.addList()
  },
})
